﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using OnlineStore.Models;
using OnlineStore.Services;

namespace OnlineStore.Web.Controllers
{


    //注入购物车服务
    [Authorize]
    public class CartController : Controller
    {
        private readonly ICartService _cartService;
        public CartController(ICartService cartService)
        {
            _cartService = cartService;
        }
        public IActionResult Index()
        {
            var userId = Convert.ToInt32(HttpContext.User.Claims.FirstOrDefault(c => c.Type == "Id").Value);
            IEnumerable<ProductInCart> products = _cartService.GetProductInCart(userId);
            return View(products);
        }

        [HttpPost]
        public async Task<IActionResult> Edit(int productId, int quantity)
        {
            await _cartService.UpdateQuantityAsync(productId, quantity);
            return RedirectToAction(nameof(Index));
        }


        public async Task<IActionResult> Delete(int productId)
        {
            await _cartService.RemoveProduct(productId);
            return RedirectToAction(nameof(Index));
        }

    }
}